import 'package:flutter/material.dart';
import 'package:xinxuan/common/dialogs/input_dialog_util.dart';
import 'package:xinxuan/common/network_image_util.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/controllers/cooperation_controller/cooperation_page_controller.dart';
import 'package:xinxuan/controllers/my_controller/my_page_controller.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:x_common_utils/utils/inkWell_util.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:xinxuan/utils/color_util.dart';
import 'package:xinxuan/utils/refresh_util.dart';

class MyPage extends StatelessWidget {

  final CommonPageController commonPageController = Get.find();
  final MyPageController controller = Get.put(MyPageController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: pageBgColor,
      body: Stack(
        children: [
          Obx(() => RefreshUtil.easyRefresh(
            scrollController: controller.scrollController,
            // onRefresh: () async {
            //   commonPageController.checkLogin(loading: false);
            // },
            slivers: [
              // SliverToBoxAdapter(
              //   child: Container(
              //     height: 169.h + ScreenUtil().statusBarHeight,
              //     padding: EdgeInsets.only(top: 84.h, bottom: 20.h),
              //     decoration: BoxDecoration(
              //       image: DecorationImage(
              //         image: AssetImage(
              //           'assets/images/my_head_bg.png'
              //         ),
              //         fit: BoxFit.cover
              //       )
              //     ),
              //     child: Column(
              //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
              //       children: [
              //         _userHead(),
              //         InkWellUtil.shakeProofInkWell(Container(
              //           padding: EdgeInsets.symmetric(horizontal: 26.w),
              //           child: Row(
              //             mainAxisAlignment: MainAxisAlignment.spaceBetween,
              //             crossAxisAlignment: CrossAxisAlignment.center,
              //             children: [
              //               _assetsItem('收入积分', '${commonPageController.userData.value.integral!.available}'),
              //               _assetsItem('消费积分', '${commonPageController.userData.value.integral!.used}'),
              //               _assetsItem('到期积分', '${commonPageController.userData.value.integral!.expired}'),
              //             ],
              //           ),
              //         ), () {
              //           Get.toNamed(
              //             '${AppRouters.COMMON_PAGE}${AppRouters.INTEGRAL_PAGE}'
              //           );
              //         })
              //       ],
              //     ),
              //   )
              // ),
              SliverToBoxAdapter(
                child: Container(
                  padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight + 40.h, bottom: 30.h),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(
                        'assets/images/my_head_bg.png'
                      ),
                      fit: BoxFit.cover
                    )
                  ),
                  child: _userHead(),
                )
              ),
              SliverToBoxAdapter(child: _orderBody(title: '盲盒订单', children: [
                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _funItem(path: 'assets/icons/icon_pending_payment.png', title: '未付款', num: commonPageController.userData.value.statistics!.seckill![0], width: 75.w, onTap: () {
                        Get.toNamed(
                          '${AppRouters.COMMON_PAGE}${AppRouters.SECKILL_ORDER_PAGE}',
                          arguments: {
                            'tabIndex': 0
                          }
                        )!.then((value) {
                          commonPageController.getUserInfo(loading: false);
                        });
                      }),
                      _funItem(path: 'assets/icons/icon_order_advance.png', title: '已预付', num: commonPageController.userData.value.statistics!.seckill![1], width: 75.w, onTap: () {
                        Get.toNamed(
                          '${AppRouters.COMMON_PAGE}${AppRouters.SECKILL_ORDER_PAGE}',
                          arguments: {
                            'tabIndex': 1
                          }
                        )!.then((value) {
                          commonPageController.getUserInfo(loading: false);
                        });
                      }),
                      _funItem(path: 'assets/icons/icon_order_wait_for.png', title: '已中签', num: commonPageController.userData.value.statistics!.seckill![2], width: 75.w, onTap: () {
                        Get.toNamed(
                          '${AppRouters.COMMON_PAGE}${AppRouters.SECKILL_ORDER_PAGE}',
                          arguments: {
                            'tabIndex': 2
                          }
                        )!.then((value) {
                          commonPageController.getUserInfo(loading: false);
                        });
                      }),
                      _funItem(path: 'assets/icons/icon_deliver_goods.png', title: '发货中', num: commonPageController.userData.value.statistics!.seckill![3], width: 75.w, onTap: () {
                        Get.toNamed(
                          '${AppRouters.COMMON_PAGE}${AppRouters.SECKILL_ORDER_PAGE}',
                          arguments: {
                            'tabIndex': 3
                          }
                        )!.then((value) {
                          commonPageController.getUserInfo(loading: false);
                        });
                      }),
                      _funItem(path: 'assets/icons/icon_order_complete.png', title: '已完成', num: commonPageController.userData.value.statistics!.seckill![4], width: 75.w, onTap: () {
                        // Get.toNamed(
                        //   '${AppRouters.COMMON_PAGE}${AppRouters.MY_COMMODITY_PAGE}'
                        // )!.then((value) {
                        //   commonPageController.getUserInfo(loading: false);
                        // });
                        Get.toNamed(
                          '${AppRouters.COMMON_PAGE}${AppRouters.SECKILL_ORDER_PAGE}',
                          arguments: {
                            'tabIndex': 4
                          }
                        )!.then((value) {
                          commonPageController.getUserInfo(loading: false);
                        });
                      }),
                    ],
                  ),
                )
              ], onTap: () {
                Get.toNamed(
                  '${AppRouters.COMMON_PAGE}${AppRouters.SECKILL_ORDER_PAGE}',
                  arguments: {
                    'tabIndex': 0
                  }
                );
              })),
              SliverToBoxAdapter(child: _orderBody(title: '商城订单', children: [
                Container(
                  // padding: EdgeInsets.symmetric(horizontal: 18.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _funItem(path: 'assets/icons/icon_payment.png', title: '待付款', num: commonPageController.userData.value.statistics!.shopping![0], width: 125.w, onTap: () {
                        Get.toNamed(
                          '${AppRouters.COMMON_PAGE}${AppRouters.STORE_ORDER_PAGE}',
                          arguments: {
                            'tabIndex': 1
                          }
                        )!.then((res) {
                          commonPageController.getUserInfo(loading: false);
                        });
                      }),
                      _funItem(path: 'assets/icons/icon_delivery_voucher.png', title: '我的提货券', num: commonPageController.userData.value.statistics!.shopping![1], width: 125.w, onTap: () {
                        Get.toNamed(
                          '${AppRouters.COMMON_PAGE}${AppRouters.STORE_ORDER_PAGE}',
                          arguments: {
                            'tabIndex': 2
                          }
                        )!.then((res) {
                          commonPageController.getUserInfo(loading: false);
                        });
                      }),
                      _funItem(path: 'assets/icons/icon_exchange.png', title: '退换/售后', num: commonPageController.userData.value.statistics!.shopping![2], width: 125.w, onTap: () {
                        Get.toNamed(
                          '${AppRouters.COMMON_PAGE}${AppRouters.STORE_ORDER_PAGE}',
                          arguments: {
                            'tabIndex': 0
                          }
                        )!.then((res) {
                          commonPageController.getUserInfo(loading: false);
                        });
                      }),
                    ],
                  ),
                )
              ], onTap: () {
                Get.toNamed(
                  '${AppRouters.COMMON_PAGE}${AppRouters.STORE_ORDER_PAGE}',
                  arguments: {
                    'tabIndex': 0
                  }
                )!.then((res) {
                  commonPageController.getUserInfo(loading: false);
                });
              })),
              SliverToBoxAdapter(child: _orderBody(title: '其他信息', showAllBtn: false, topPadding: false, children: _getOtherItem().map((item) {
                return Container(
                  padding: EdgeInsets.only(top: 12.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: item,
                  ),
                );
              }).toList())),
            ]
          )),
          Positioned(
            child: Obx(() => Container(
              height: 40.h + ScreenUtil().statusBarHeight,
              padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Color.fromRGBO(254, 7, 15, controller.titleBarOpacity.value),
                    Color.fromRGBO(255, 38, 99, controller.titleBarOpacity.value)
                  ],
                )
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Container(
                    margin: EdgeInsets.only(right: 16.w),
                    child: InkWellUtil.shakeProofInkWell(
                      Image.asset(
                        'assets/icons/icon_setting.png',
                        width: 20.w,
                        height: 20.w,
                      ), () {
                        Get.toNamed('${AppRouters.COMMON_PAGE}${AppRouters.MY_INFO_PAGE}');
                      },
                      hoverColor: Colors.transparent,
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent
                    ),
                  ),
                  GetBuilder<CooperationPageController>(
                    init: CooperationPageController(),
                    builder: (cooperationPageController) {
                      // return  _funItem(path: 'assets/icons/icon_invitation_r.png', title: '邀请加入', width: 80.w, onTap: () {
                      //   _invitation(cooperationPageController);
                      // });
                      return Container(
                        margin: EdgeInsets.only(right: 16.w),
                        child: InkWellUtil.shakeProofInkWell(
                          Image.asset(
                            'assets/icons/icon_invitation_w.png',
                            width: 20.w,
                            height: 20.w,
                          ), () {
                            _invitation(cooperationPageController);
                          },
                          hoverColor: Colors.transparent,
                          splashColor: Colors.transparent,
                          highlightColor: Colors.transparent
                        ),
                      );
                    },
                  ),
                ],
              ),
            ))
          )
        ],
      ),
    );
  }

  /// 用户信息
  Widget _userHead() {
    if (!commonPageController.isAuthenticated.value) {
      return InkWellUtil.shakeProofInkWell(Container(
        height: 54.w,
        padding: EdgeInsets.only(left: 30.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Image.asset(
                  'assets/icons/icon_default_head.png',
                  width: 54.w,
                  height: 54.w,
                ),
                SizedBox(width: 12.w),
                Text(
                  '请点击登录',
                  style: TextStyle(
                    color: textWhiteColor,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold
                  ),
                )
              ],
            )
          ],
        ),
      ), () {
        Get.toNamed('${AppRouters.COMMON_PAGE}${AppRouters.LOGIN_PAGE}');
      });
    }
    return InkWellUtil.shakeProofInkWell(Container(
      height: 54.w,
      padding: EdgeInsets.only(left: 30.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              NetworkImageUtil(
                url: commonPageController.userData.value.avatar ?? '',
                nickname: commonPageController.userData.value.nickname ?? '', 
                width: 54.w, 
                height: 54.w
              ),
              SizedBox(width: 12.w),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    commonPageController.userData.value.nickname ?? '',
                    style: TextStyle(
                      color: textWhiteColor,
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold
                    ),
                  ),
                  SizedBox(height: 6.w),
                  Text(
                    '邀请码：${commonPageController.userData.value.invitationCode}',
                    style: TextStyle(
                      color: textWhiteColor,
                      fontSize: 14.sp
                    ),
                  ),
                ],
              )
            ],
          ),
          InkWellUtil.shakeProofInkWell(Container(
            height: 30.h,
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: bgWhiteColor_90,
              borderRadius: BorderRadius.horizontal(left: Radius.circular(20.w)),
              boxShadow: [
                BoxShadow(
                  color: bgMyIntegral,
                  offset: Offset(0, 2.h),
                  blurRadius: 10.h
                )
              ]
            ),
            child: Text(
              '${commonPageController.userData.value.integral!.available}积分',
              style: TextStyle(
                color: mainTextColor,
                fontWeight: FontWeight.bold,
                fontSize: 12.sp
              ),
            ),
          ), () {
            Get.toNamed(
              '${AppRouters.COMMON_PAGE}${AppRouters.INTEGRAL_PAGE}'
            );
          })
        ],
      ),
    ), () {
      Get.toNamed('${AppRouters.COMMON_PAGE}${AppRouters.MY_INFO_PAGE}');
    });
  }

  /// 资产Item
  // Widget _assetsItem(String title, String value) {
  //   return Column(
  //     children: [
  //       Text(
  //         title,
  //         style: TextStyle(
  //           color: textWhiteColor,
  //           fontSize: 12.sp
  //         ),
  //       ),
  //       SizedBox(height: 8.h),
  //       Text(
  //         value,
  //         style: TextStyle(
  //           color: textWhiteColor,
  //           fontSize: 18.sp,
  //           fontWeight: FontWeight.bold
  //         ),
  //       )
  //     ],
  //   );
  // }

  /// 订单Body
  Widget _orderBody({required String title, required List<Widget> children, bool showAllBtn = true,bool topPadding = true, Function? onTap}) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      child: Container(
        color: bgWhiteColor,
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 13.w),
              child: Container(
                height: 54.h,
                padding: EdgeInsets.symmetric(horizontal: 3.w),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: lineColor,
                      width: 1.w
                    )
                  )
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      title,
                      style: TextStyle(
                        color: textBlackColor,
                        fontSize: 16.sp
                      ),
                    ),
                    showAllBtn ? InkWellUtil.shakeProofInkWell(Row(
                      children: [
                        Text(
                          '全部订单',
                          style: TextStyle(
                            color: textSubtitleColor,
                            fontSize: 14.sp
                          ),
                        ),
                        SizedBox(width: 8.w),
                        Image.asset(
                          'assets/icons/icon_arrow_right_w.png',
                          width: 8.w,
                          height: 15.h,
                        )
                      ],
                    ), () {
                      onTap!();
                    }) : Container()
                  ],
                ),
              ),
            ),
            Container(
              width: 375.w,
              padding: EdgeInsets.only(top: topPadding ? 12.h : 0, bottom: 20.h),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: children,
              ),
            ),
            SizedBox(height: 4.h)
          ],
        ),
      ),
    );
  }

  /// 功能项
  Widget _funItem({required String title, required path, required double width, required Function onTap, int num = 0}) {
    return InkWellUtil.shakeProofInkWell(Container(
      width: width,
      padding: EdgeInsets.only(top: 6.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Stack(
            children: [
              Container(
                width: 42.w,
                height: 36.w,
                alignment: Alignment.center,
                child: Image.asset(
                  path,
                  width: 24.w,
                  height: 24.w,
                ),
              ),
              Positioned(
                top: 0,
                right: 0,
                child: _angleMark(num)
              )
            ],
          ),
          Text(
            title,
            style: TextStyle(
              color: textBlackColor,
              fontSize: 14.sp
            ),
          )
        ],
      ),
    ), () => onTap());
  }

  /// 获取其他Item
  List<List<Widget>> _getOtherItem() {
    List<Widget> children = [
      GetBuilder<CooperationPageController>(
        init: CooperationPageController(),
        builder: (cooperationPageController) {
          return  _funItem(path: 'assets/icons/icon_invitation_r.png', title: '邀请加入', width: 93.w, onTap: () {
            _invitation(cooperationPageController);
          });
        },
      ),
      // _funItem(path: 'assets/icons/icon_upgrades.png', title: '会员升级', width: 80.w, onTap: () {
      //   Get.toNamed('${AppRouters.COMMON_PAGE}${AppRouters.UPGRADES_PAGE}');
      // }),
      _funItem(path: 'assets/icons/icon_update_password.png', title: '修改密码', width: 93.w, onTap: () {
        Get.toNamed('${AppRouters.COMMON_PAGE}${AppRouters.MY_INFO_PAGE}${AppRouters.UPDATE_PASSWORD_PAGE}');
      }),
      _funItem(path: 'assets/icons/icon_privacy.png', title: '隐私政策', width: 93.w, onTap: () {
        Get.toNamed(
          '${AppRouters.COMMON_PAGE}${AppRouters.ARTICLE_DETAIL_PAGE}',
          arguments: {
            'articleId': 2,
            'title': '隐私政策'
          }
        );
      }),
      // _funItem(path: 'assets/icons/icon_gift_y.png', title: '赠品', width: 80.w, onTap: () {
      //   Get.toNamed(
      //     '${AppRouters.COMMON_PAGE}${AppRouters.GIFT_PAGE}',
      //   );
      // }),
      _funItem(path: 'assets/icons/icon_check_update.png', title: '版本更新', width: 93.w, onTap: () {
        commonPageController.checkAppVersion();
      }),
      _funItem(path: 'assets/icons/icon_wechat.png', title: '我的微信号', width: 93.w, onTap: () {
        Get.dialog(StatefulBuilder(
          builder: (context, setButtomSheetState) {
            return InputDialogUtil(
              title: '修改微信号',
              hintText: '请输入微信号',
              defaultValue: '${commonPageController.userData.value.wechat}',
              onChenge: (value) {
                commonPageController.wechat = value;
              },
              onSubmit: () {
                commonPageController.editUserWechat();
              }
            );
          }
        ));
      }),
      commonPageController.userData.value.isWriteoffOfficer == 1 ? _funItem(path: 'assets/icons/icon_qrcode_scan.png', title: '扫码核销', width: 93.w, onTap: () {
        commonPageController.startScan();
      }) : Container(width: 93.w),
      Container(width: 93.w),
      Container(width: 93.w),
    ];
    int length = 8 - children.length;
    for (int i = 0; i < length; i++) {
      children.add(Container());
    }

    List<List<Widget>> pageArr = [];
    List<Widget> itemArr = [];
    children.forEach((item) {
      if(itemArr.length == 4) {
        itemArr=[];
      }
      if(itemArr.length == 0) {
        pageArr.add(itemArr);
      }
      itemArr.add(item);
    });
    return pageArr;
  }

  /// 角标
  Widget _angleMark(int number) {
    if (number <= 0) {
      return Container();
    }
    if (number < 10) {
      return Container(
        width: 16.w,
        height: 16.w,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16.w),
          color: bgMainColor,
          border: Border.all(
            width: 1.w,
            color: bgWhiteColor
          )
        ),
        child: Text(
          '$number',
          style: TextStyle(
            color: textWhiteColor,
            fontSize: 12.sp
          ),
        ),
      );
    }
    if (number <= 99) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 1.h),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16.w),
          color: bgMainColor,
          border: Border.all(
            width: 1.w,
            color: bgWhiteColor
          )
        ),
        child: Text(
          '$number',
          style: TextStyle(
            color: textWhiteColor,
            fontSize: 12.sp
          ),
        ),
      );
    }
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 1.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16.w),
        color: bgMainColor,
        border: Border.all(
          width: 1.w,
          color: bgWhiteColor
        )
      ),
      child: Text(
        '99+',
        style: TextStyle(
          color: textWhiteColor,
          fontSize: 12.sp
        ),
      ),
    );
  }

  _invitation(CooperationPageController cooperationPageController) {
    if (!commonPageController.isRevirew.value) {
      commonPageController.tabIndex.value = 1;
    }   
    cooperationPageController.joinTeam(); 
    // Get.dialog(StatefulBuilder(
    //   builder: (context, setButtomSheetState) {
    //     return InputDialogUtil(
    //       title: '邀请码加入',
    //       hintText: '请输入邀请码',
    //       defaultValue: '',
    //       maxLength: 10,
    //       onChenge: (value) {
    //         cooperationPageController.invitationCode.value = value;
    //       },
    //       onSubmit: () {
    //         cooperationPageController.invitations();
    //       }
    //     );
    //   }
    // ));
  }

}